/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controladores;

import Controladores.exceptions.NonexistentEntityException;
import Controladores.exceptions.PreexistingEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entidades.Appointment;
import entidades.Owner;
import entidades.Person;
import entidades.Veterinarian;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaBuilder;

/**
 *
 * @author Gatoper
 */
public class VeterinarianJpaController implements Serializable {

    public VeterinarianJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Veterinarian veterinarian) throws PreexistingEntityException, Exception {
        if (veterinarian.getAppointments() == null) {
            veterinarian.setAppointments(new ArrayList<Appointment>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Appointment> attachedAppointments = new ArrayList<Appointment>();
            for (Appointment appointmentsAppointmentToAttach : veterinarian.getAppointments()) {
                appointmentsAppointmentToAttach = em.getReference(appointmentsAppointmentToAttach.getClass(), appointmentsAppointmentToAttach.getId());
                attachedAppointments.add(appointmentsAppointmentToAttach);
            }
            veterinarian.setAppointments(attachedAppointments);
            em.persist(veterinarian);
            for (Appointment appointmentsAppointment : veterinarian.getAppointments()) {
                Veterinarian oldVeterinarianOfAppointmentsAppointment = appointmentsAppointment.getVeterinarian();
                appointmentsAppointment.setVeterinarian(veterinarian);
                appointmentsAppointment = em.merge(appointmentsAppointment);
                if (oldVeterinarianOfAppointmentsAppointment != null) {
                    oldVeterinarianOfAppointmentsAppointment.getAppointments().remove(appointmentsAppointment);
                    oldVeterinarianOfAppointmentsAppointment = em.merge(oldVeterinarianOfAppointmentsAppointment);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findVeterinarian(veterinarian.getName()) != null) {
                throw new PreexistingEntityException("Veterinarian " + veterinarian + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Veterinarian veterinarian) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Veterinarian persistentVeterinarian = em.find(Veterinarian.class, veterinarian.getName());
            List<Appointment> appointmentsOld = persistentVeterinarian.getAppointments();
            List<Appointment> appointmentsNew = veterinarian.getAppointments();
            List<Appointment> attachedAppointmentsNew = new ArrayList<Appointment>();
            for (Appointment appointmentsNewAppointmentToAttach : appointmentsNew) {
                appointmentsNewAppointmentToAttach = em.getReference(appointmentsNewAppointmentToAttach.getClass(), appointmentsNewAppointmentToAttach.getId());
                attachedAppointmentsNew.add(appointmentsNewAppointmentToAttach);
            }
            appointmentsNew = attachedAppointmentsNew;
            veterinarian.setAppointments(appointmentsNew);
            veterinarian = em.merge(veterinarian);
            for (Appointment appointmentsOldAppointment : appointmentsOld) {
                if (!appointmentsNew.contains(appointmentsOldAppointment)) {
                    appointmentsOldAppointment.setVeterinarian(null);
                    appointmentsOldAppointment = em.merge(appointmentsOldAppointment);
                }
            }
            for (Appointment appointmentsNewAppointment : appointmentsNew) {
                if (!appointmentsOld.contains(appointmentsNewAppointment)) {
                    Veterinarian oldVeterinarianOfAppointmentsNewAppointment = appointmentsNewAppointment.getVeterinarian();
                    appointmentsNewAppointment.setVeterinarian(veterinarian);
                    appointmentsNewAppointment = em.merge(appointmentsNewAppointment);
                    if (oldVeterinarianOfAppointmentsNewAppointment != null && !oldVeterinarianOfAppointmentsNewAppointment.equals(veterinarian)) {
                        oldVeterinarianOfAppointmentsNewAppointment.getAppointments().remove(appointmentsNewAppointment);
                        oldVeterinarianOfAppointmentsNewAppointment = em.merge(oldVeterinarianOfAppointmentsNewAppointment);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = veterinarian.getName();
                if (findVeterinarian(id) == null) {
                    throw new NonexistentEntityException("The veterinarian with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Veterinarian veterinarian;
            try {
                veterinarian = em.getReference(Veterinarian.class, id);
                veterinarian.getName();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The veterinarian with id " + id + " no longer exists.", enfe);
            }
            List<Appointment> appointments = veterinarian.getAppointments();
            for (Appointment appointmentsAppointment : appointments) {
                appointmentsAppointment.setVeterinarian(null);
                appointmentsAppointment = em.merge(appointmentsAppointment);
            }
            em.remove(veterinarian);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Veterinarian> findVeterinarianEntities() {
        return findVeterinarianEntities(true, -1, -1);
    }

    public List<Veterinarian> findVeterinarianEntities(int maxResults, int firstResult) {
        return findVeterinarianEntities(false, maxResults, firstResult);
    }

    private List<Veterinarian> findVeterinarianEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Veterinarian.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Veterinarian findVeterinarian(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Veterinarian.class, id);
        } finally {
            em.close();
        }
    }
    public List<Veterinarian> findVeterinarianByProp(String prop,String c) {
        EntityManager em = getEntityManager();
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Veterinarian> cq = cb.createQuery(Veterinarian.class);
            Root<Veterinarian> veterinarian = cq.from(Veterinarian.class);
            cq.select(veterinarian).where(cb.like(veterinarian.<String>get(prop), "%" + c + "%"));
            Query q = em.createQuery(cq);
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    public List<Veterinarian> findVeterinariannm(String c) {
        return findVeterinarianByProp("name",c);
        /*EntityManager em = getEntityManager();
         try {
         String sql="select * from hpvas.veterinarian where name like '%" + c + "%';";
         Query query = em.createNativeQuery(sql);
         return query.getResultList();
         } finally {
         em.close();
         }*/
    }
    
    public List<Veterinarian> findVeterinarianBySSN(String c) {
        EntityManager em = getEntityManager();
        try {
            String sql = "select veterinarian.name from hpvas.veterinarian join hpvas.person on (veterinarian.name=person.name) where person.SSN like '%" + c + "%';";
            Query query = em.createNativeQuery(sql);
            List<String> a = query.getResultList();
            List<Veterinarian> retorno = new Vector();
            for (int i = 0; i < a.size(); i++) {
                retorno.add(findVeterinarian(a.get(i)));
            }
            return retorno;
        } finally {
            em.close();
        }
    }
    public String findPetNames(String c){
        EntityManager em = getEntityManager();
        try {
            String sql = "SELECT DISTINCT(PET_name) FROM (((medicalrecord join medicalrecord_appointment on medicalrecord.ID=medicalrecord_appointment.Medicalrecord_ID) " +
"join appointment on appointment.ID=medicalrecord_appointment.appointment_ID) join veterinarian on (veterinarian.name=appointment.VETERINARIAN_name)) where veterinarian.name like '%"+c+"%';";
            Query query = em.createNativeQuery(sql);
            List<String> a = query.getResultList();
            String retorno = " ";
            for (int i = 0; i < a.size(); i++) {
                retorno+=a.get(i)+", ";
            }
            if (retorno.length()>1){
                retorno=retorno.substring(0, retorno.length()-2);
            }
            return retorno;
        } finally {
            em.close();
        }
    }

    public int getVeterinarianCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Veterinarian> rt = cq.from(Veterinarian.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
